package com.example.utils;

import com.example.entity.User;
import com.example.req.UserReq;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class CopyUtil {

    /**
     * 单体复制
     * @param source 源对象
     * @param clazz 目的对象的类
     * @param <T> 目的对象的泛型
     * @return 复制后的目的对象
     */
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BeanUtils.copyProperties(source, obj);
        return obj;
    }

    /**
     * 列表复制
     */
    public static <T> List<T> copyList(List source, Class<T> clazz) {
        List<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)){
            for (Object c: source) {
                T obj = copy(c, clazz);
                target.add(obj);
            }
        }
        return target;
    }


    @Test
    public void  sa(){
        List<UserReq> source = new ArrayList<>();
        UserReq tmp = new UserReq();
        tmp.setPhone("12");
        source.add(tmp);
        UserReq tmp2 = new UserReq();

        tmp2.setCity("223");
        source.add(tmp2);
        List<User> ans = copyList(source, User.class);
        
        System.out.println(ans);
    }



}
